package com.missilike.core.service.impl;

import com.missilike.core.domain.BaiDuMapProperties;
import com.missilike.core.service.IBaiduMapService;
import com.missilike.core.utils.BaiduMapComponent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.LinkedHashMap;
import java.util.Map;

@Slf4j
@Service
public class BaiduMapServiceImpl implements IBaiduMapService {

    private final BaiduMapComponent baiduMapComponent;
    private final RestTemplate restTemplate;
    private final BaiDuMapProperties baiDuMapProperties;

    private static final String SERVICE_URL="http://api.map.baidu.com";
    private static final String  LOCATION_IP_URL="/location/ip?";

    public BaiduMapServiceImpl(BaiduMapComponent baiduMapComponent, RestTemplate restTemplate, BaiDuMapProperties baiDuMapProperties) {
        this.baiduMapComponent = baiduMapComponent;
        this.restTemplate = restTemplate;
        this.baiDuMapProperties = baiDuMapProperties;
    }

    public Object getAddress(String ip){
        Map paramsMap = new LinkedHashMap();
        paramsMap.put("ip", ip);
        paramsMap.put("coor", "bd09ll");
        String sn= baiduMapComponent.encoderSn(LOCATION_IP_URL,paramsMap);
        String param="ip=${ip}&sn=${sn}&coor=bd09ll&ak="+baiDuMapProperties.getAk();
        Object object=sendMessages(SERVICE_URL+LOCATION_IP_URL+param.replace("${ip}",ip).replace("${sn}",sn),Object.class);
        return object;

    };


    //获取微信请求
    private <T> T sendMessages(String url, Class<T> tClass) {
        HttpEntity entity = new HttpEntity(null, createHeaders());
        log.info("【Wechat】 sending to url = {} ", url);
        ResponseEntity<T> responseEntity = null;
        try {
            responseEntity = restTemplate.exchange(url, HttpMethod.GET, entity, tClass, entity);
            log.info("【Wechat】 response for url {} result ={}", url, responseEntity);
            return responseEntity.getBody();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private HttpHeaders createHeaders() {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-type", MediaType.APPLICATION_JSON_UTF8_VALUE);
        return headers;
    }
}
